<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { pageitemApi } from '@T2/service/api.ts';
import * as echarts from "echarts";
import vueECharts from "vue-echarts";
import { getOptions, } from './utils/options.js';
import { exchangeFnc, } from './utils/exchange.js';
import SetPLCPopup from './components/setPLCPopup.vue';
import NumberCharts from './components/numberCharts.vue';

const { zPopup, disabled } = defineProps({
  zPopup: {
    type: Object,
    required: true,
  },
  disabled: {
    type: Boolean,
    default: true,
  }
});
const Resd = reactive({
  bgImgUsed: false,
	bgImg: '',
  vButShow: false,
  vButNums: 0,
  gifList: [],
  needTimer: {
    // 250: [],
  },
});
const sizeData = reactive({
  width: 100,
  height: 100,
});
onMounted(() => {
  getPageItem();
});
const getPageItem = () => {
  if (zPopup.fnc === '弹出画面' && zPopup.popupID) {
    pageitemApi({
      method: 'get',
      params: {
        page: 1,
        ordering: "-create_time",
        page_id: zPopup.popupID,
      },
    }).then(res => {
      let { results, } = res;
      let gitem = results.find(i => i.item_type === 'globalNormal');
      if (gitem) {
        setSizeData(gitem);
        initPageitem(results, '弹出画面');
      }
    });
  } else if (zPopup.fnc === '公共弹窗' && zPopup.prefix) {
    pageitemApi({
      method: 'get',
      params: {
        page: 1,
        ordering: "-create_time",
        page_id: zPopup.popupID,
        prefix: zPopup.prefix,
      },
    }).then(res => {
      let { results, } = res;
      let gitem = results.find(i => i.item_type === 'globalNormal');
      if (gitem) {
        setSizeData(gitem);
        initPageitem(results, '公共弹窗');
      }
    });
  }
}
const setSizeData = (gitem) => {
  let front = JSON.parse(gitem.front_data);
  sizeData.width = front.xAxisMax;
  sizeData.height = front.yAxisMax;
}

/*定时器*/
const resTimer = reactive({
  refresh: null,
  itemList: [],
});
const chartRef = ref(null);
const option = reactive(getOptions());
const initPageitem = (data, ptype = '弹出画面') => {
  option.series = [];
  Resd.gifList = [];
  Resd.needTimer = {
    // 250: [],
  };
  resTimer.itemList.forEach((item, index) => {
    clearInterval(item);
  });
  data.forEach((item, index) => {
    let type = item.item_type, series = JSON.parse(item.front_data);
    if (type === "globalNormal") {
      let { backgroundColor, xAxisMax, yAxisMax, bgImg, bgImgUsed } = series;
      option.backgroundColor = backgroundColor;
      option.xAxis.max = xAxisMax;
      option.yAxis.max = yAxisMax;
      Resd.bgImg = bgImg;
      Resd.bgImgUsed = bgImgUsed;
    } else if (['text01', 'number01', 'shape01', 'bar01', 'line01', 'vButton01', 'switch01', 'gauge01'].includes(type)) {
      series = exchangeFnc(item, 1, ptype);
      if (!series) {
        return;
      }
      option.series.push(series);
    } else if (['picture01'].includes(type)) {
      series = exchangeFnc(item, 1, ptype);
      if (!series) {
        return;
      }
      let {symbol, symbolRotate, symbolSize, value} = series.data[0];
      let arr1 = symbol.split('.gif'), arr2 = symbol.split('.GIF');
      if ((arr1.length === 2 && !arr1[1]) || (arr2.length === 2 && !arr2[1])) {
        if (series.data[0].itemStyle.opacity) {
          Resd.gifList.push({
            symbol: symbol.split('image://')[1],
            symbolRotate,
            symbolSize,
            value,
          });
        }
      } else {
        option.series.push(series);
      }
    } else if (type === "pipeline01") {
      series = exchangeFnc(item, 1, ptype);
      if (!series) {
        return;
      }
      option.series.push(series);
      const nowIndex = option.series.length - 1;
      if (series.data[0].statusT) {
        let tempSpeed = series.data[0].statusT.speed, moveTime = series.data[0].statusT.moveTime;
        if (tempSpeed) {
          if (Resd.needTimer[moveTime]) {
            Resd.needTimer[moveTime].push([nowIndex, tempSpeed]);
          } else {
            Resd.needTimer[moveTime] = [];
            Resd.needTimer[moveTime].push([nowIndex, tempSpeed]);
          }
        }
      }
    }
  });
  analysisPageitem();
}
const analysisPageitem = () => {
  for (const item in Resd.needTimer) {
    let timer = setInterval(function () {
      Resd.needTimer[item].forEach((arr, index) => {
        let lineStyle = option.series[arr[0]].data[2].lineStyle, mov = (lineStyle.type[0] + lineStyle.type[1])*arr[1];
        lineStyle.dashOffset -= arr[1];
        if (lineStyle.dashOffset === mov || lineStyle.dashOffset === -mov) {
          lineStyle.dashOffset = 0;
        }
      });
    }, +item);
    resTimer.itemList.push(timer);
  }
  if (chartRef.value.chart) {
    // chartRef.value.chart.clear();//不知道能不能解决缓存问题
    chartRef.value.chart.setOption(option, true);
  }
}

const SetPLCRef = ref(null);
const vueEChartsClick = async (event) => {
  let editObj = option.series[event.seriesIndex];
  let dataIndex = event.dataIndex;
  if (['text01', 'picture01'].includes(editObj.editType)) {
    let pageT = editObj.data[dataIndex].pageT;
    if (pageT?.fnc === '切换页面') {
      zPopup.popupID = pageT.page;
      getPageItem();
    }
  } else if (editObj.editType === 'vButton01') {
    Resd.vButShow = true;
    Resd.vButNums+=1;
  } else if (editObj.editType === 'number01') {
    if (editObj.data[dataIndex]?.statusT?.rw === '读写') {
      SetPLCRef.value.checkPopup(editObj, dataIndex);
    } else {
      showNumberCharts(editObj);
    }
  } else if (editObj.editType === 'switch01') {
    SetPLCRef.value.checkPopup(editObj, dataIndex);
  }
}

onMounted(() => {
  resTimer.refresh = setInterval(() => {
    getPageItem();
  }, 15000);
});
onBeforeUnmount(() => {
  clearInterval(resTimer.refresh);
  resTimer.refresh = null;
  resTimer.itemList.forEach((item, index) => {
    clearInterval(item);
  });
  resTimer.itemList = [];
});

/* 报警规则配置 */
const NumberPopResd = reactive({
  visible: false,
  editObj: {},
});
const showNumberCharts = (editObj) => {
  NumberPopResd.editObj = editObj;
  NumberPopResd.visible = true;
}
const closeNumberPop = () => {
  NumberPopResd.visible = false;
  NumberPopResd.editObj = {};
}
</script>

<template>
  <div class="commonTitle" v-if="zPopup.fnc === '公共弹窗'">{{zPopup.title}}</div>
  <label v-if="zPopup.fnc === '公共弹窗'">{{zPopup.title}}</label>
  
  <div
    class="box_canvas"
    :style="{
      width: sizeData.width + 'px',
      height: sizeData.height + 'px',
      minWidth: sizeData.width + 'px',
      minHeight: sizeData.height + 'px',
    }"
  >
    <div class="backColor">
    	<img :src="Resd.bgImg" v-if="Resd.bgImgUsed" />
    </div>
    
    <vueECharts
      ref="chartRef"
      autoresize
      :option="option"
      @click="vueEChartsClick"
    >
    </vueECharts>
    
    <template v-if="Resd.gifList.length" v-for="(gif, index) in Resd.gifList">
      <div
        class="gifC"
        :style="{
          transform: `rotate(${-gif.symbolRotate}deg) translate(-50%, -50%)`,
          width: gif.symbolSize[0] + 'px',
          height: gif.symbolSize[1] + 'px',
          left: gif.value[0] + 'px',
          top: sizeData.height - gif.value[1] + 'px',
        }"
      >
        <img
          :src="gif.symbol"
          :width="gif.symbolSize[0]"
          :height="gif.symbolSize[1]"
        />
      </div>
    </template>
  </div>
  
  <SetPLCPopup ref="SetPLCRef" :disabled="disabled" />
  
  <NumberCharts
    v-if="NumberPopResd.visible"
    :editObj="NumberPopResd.editObj"
    @close="closeNumberPop"
  />
</template>

<style lang="scss" scoped>
.commonTitle {
  background-color: #0a576f;
  border-radius: 10px 10px 0 0;
  font-size: 18px;
  min-width: 100px;
  color: rgba(0, 0, 0, 0);
  height: 40px;
  text-align: center;
  position: absolute;
  left: 50%;
  transform: translateX(-50%) perspective(40px) rotateX(20deg);
  transform-origin: center bottom;
  top: -39px;
  &::before,
  &::after {
    content: '';
    position: absolute;
    width: 20px;
    height: 20px;
    bottom: 0;
    background-color: #ffffff;
  }
  &::before {
    left: -19px;
    background: radial-gradient(circle at 0 0, transparent 20px, #0a576f 20px);
  }
  &::after {
    right: -19px;
    background: radial-gradient(circle at 100% 0, transparent 20px, #0a576f 20px);
  }
}
label {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  top: -28px;
  height: 28px;
  line-height: 28px;
  // background-color: rgba(0, 22, 30, 1);
  color: #ffffff;
  // font-weight: bold;
  text-align: center;
  font-size: 18px;
  text-shadow: 1px 1px 1px rgba(7, 53, 73, 1);
  -webkit-text-stroke: 0.4px rgba(54, 132, 162, 1);
}
.noBorder {
  
}
.box_canvas {
  position: relative;
  // border-image-source: radial-gradient(69% 69%, transparent 0px, transparent 100%, cyan 100%);
  // border-image-slice: 1;
  // border-width: 1px;
  // border-style: solid;
  .backColor {
  	position: absolute;
  	left: 0;
  	top: 0;
  	width: 100%;
  	height: 100%;
  	img {
  		width: 100%;
  		height: 100%;
  	}
  }
  .gifC {
    position: absolute;
    left: 20px;
  }
}
</style>
